import Vue from 'vue'
import Router from 'vue-router';
import store from '@/store/index';
import { deepAddRoute } from '@/utils/menu.js'
//导入
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { setCookie,getCookie } from '@/utils/cookie.js'

Vue.use(Router)

export const constantRoutes = [
    {
        path: '/',
        redirect: '/home',
        meta:{ title: '',  }
    },
    {
        path: '/home',
        component: () => import('../views/home/index.vue'),
    },
    // {
    //     path: '/dev',
    //     component: () => import('../views/dev/index.vue'),
    // },
    // {
    //     path: '/handleDetail',
    //     component: () => import('../views/home/handleDetail/index.vue'),
    // },
//     {
//         path: '/diskInfo',
//         component: () => import('../views/diskInfo/index.vue'),
//     },
//     {
//         path: '/taxClass',
//         component: () => import('../views/taxClass/index.vue'),
//     },
//     {
//         path: '/availableTax',
//         component: () => import('../views/availableTax/index.vue'),
//     },
//     { //
//         path: '/creditLimit',
//         component: () => import('../views/creditLimit/index.vue'),
//     },
//     { //
//         path: '/preShareCode',
//         component: () => import('../views/preShareCode/index.vue'),
//     },
//     { //
//         path: '/invoiceTemplate',
//         component: () => import('../views/invoiceTemplate/index.vue'),
//     },
//     { //
//         path: '/myAgent',
//         component: () => import('../views/myAgent/index.vue'),
//     },
//     { //
//         path: '/handleDetail',
//         component: () => import('../views/home/handleDetail/index.vue'),
//     },
//     { //
//         path: '/handInvoiceAdd',
//         component: () => import('../views/handInvoiceAdd/index.vue'),
//     },
//     { //
//         path: '/invoicedInfo',
//         component: () => import('../views/invoicedInfo/index.vue'),
//     },


//     {
//         path: '/home',
//         component: () => import('../views/home/index.vue'),
//     },
//     {
//         path: '/dev',
//         component: () => import('../views/dev/index.vue'),
//     },
//     {
//         path: '/custom',
//         component: () => import('../views/custom/index.vue'),
//     },


// // part2
//     {  // 4.1企业商品及服务信息管理
//         path: '/serviceInformationManage',
//         component: () => import('../views/serviceInformationManage/index.vue'),
//     },
//     {  // 4.2用户基本信息
//         path: '/userBasicInformation',
//         component: () => import('../views/userBasicInformation/index.vue'),
//     },
//     {  // 4.3
//         path: '/flowInvoice',
//         component: () => import('../views/flowInvoice/index.vue'),
//     },
//     {  // 4.4
//         path: '/manualNegativeInvoice',
//         component: () => import('../views/manualNegativeInvoice/index.vue'),
//     },
//     {  // 4.6
//         path: '/invoiceSummryConfirm',
//         component: () => import('../views/invoiceSummryConfirm/index.vue'),
//     },

//     {  // 4.7红票确认单 申请
//         path: '/redConfirmApply',
//         component: () => import('../views/redConfirmApply/index.vue'),
//     },
//     {   // 4.8红票确认单 申请
//         path: '/redConfirmForm',
//         component: () => import('../views/redConfirmForm/index.vue'),
//     },

//     // part3
//     {   // 发票归集
//         path: '/invoiceCollection',
//         component: () => import('../views/invoiceCollection/index.vue'),
//     },
//     {   // 发票查验
//         path: '/invoiceVericication',
//         component: () => import('../views/invoiceVericication/index.vue'),
//     },
//     {
//         path: '/realEstateRegionalAllocation',
//         component: () => import('../views/realEstateRegionalAllocation/index.vue'),
//     },




    {
        path: '/404',
        component: () => import('@/views/404'),
        hidden: true
    },

    {path: '*', redirect: '/404', hidden: true}
]


const createRouter = () => new Router({
    scrollBehavior: () => ({y: 0}),
    mode: process.env.NODE_ENV === 'devServe'? 'hash' : 'history', // require service support
    routes: constantRoutes
})



const router = createRouter()
router.beforeEach(async (to, form, next) => {
    document.title = '新华保险增值税管理系统'
    // NProgress.start()
    try { 
        let ww = location.href.split('?token=');
        let token = ww[1];
        if (token) {
            setCookie('pathToken', token)
        }else if(getCookie('pathToken')){
            sessionStorage.setItem('tokenIframe', getCookie('pathToken'))
            sessionStorage.setItem('refreshTokenCache', '')
            setCookie('pathToken', '')
        }
        if(!store.state.user.getedRouteList){
            let res =   await store.dispatch('user/getRouteList');
            if(res){
                let rList = store.state.user.routeList
                if(rList&& rList.length){
                    router.addRoute({
                        "path": "/home",
                        "component": () => import('../views/home/index.vue')
                    })




                    for(let index = 0; index < rList.length; index++) {
                        const element = rList[index];
                        if(element.children && element.children.length){
                             await deepAddRoute(element.children,router)
                        }else{
                            if(element.path === '/dev'){
                                router.addRoute({
                                    "path": "/dev",
                                    "component": () => import('../views/dev/index.vue')
                                })
                            }
                        }
                    }
                }

                let routeInfoCache = sessionStorage.getItem('routeCache');
                if(routeInfoCache){
                    routeInfoCache = JSON.parse(routeInfoCache)
                }
                if((to.path == '/404') && (form.fullPath == '/') && (routeInfoCache)){
                        store.commit('homeStore/setRouterInfo', {
                            title: routeInfoCache.name,
                            name: routeInfoCache.name,
                            path:  routeInfoCache.path,
                        });
                        store.commit('homeStore/setEditableTabsValue', routeInfoCache.name);
                        next(routeInfoCache.path)
                }else if((to.path == '/404') && (form.fullPath == '/') && to.redirectedFrom){
                        let curInfo =   store.state.user.routeTreeToList.reduce((pre,cur)=>{
                            if(cur.path == to.redirectedFrom){
                                return cur
                            }else{
                                return pre
                            }
                        },{})
                        if(curInfo.name){
                            let obj = {
                                title: curInfo.name,
                                name: curInfo.name,
                                path:  curInfo.path,
                            }
 
                            next(obj.path)
                            setTimeout(()=>{
                                store.commit('homeStore/setEditableTabsValue', obj.name);
                                store.commit('homeStore/setRouterInfo', obj); // 跳了
                            })
                        }else{
                            next(to.redirectedFrom)
                        }

                }else{
                        next()
                }
            }else{
                next('/404')
            }
        }else{
            sessionStorage.setItem('routeCache', JSON.stringify({
                path:to.fullPath,
                name:to.name
            }))
            next()
        }
    } catch (error) {
        console.log(error)
        next()
    }

})
router.afterEach(() => {
    NProgress.done()
  })

export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher // reset router
}

export default router










